package server.common.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import server.common.message.Header;
import server.common.message.NettyMessage;
import server.common.message.NettyMessageFactory;

/**
 * Created by xiangliyou on 17-9-23.
 *
 * @DESCRIPTION
 *  服务端的心跳应答
 */
public class HeartBeatRespHandler extends SimpleChannelInboundHandler {

    //心跳次数计数
    private int heartbeatCount = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage message = (NettyMessage) msg;
        System.out.println("HeartBeatRespHandler  " + msg);
        if (message.getHeader() != null
                && message.getHeader().getType() == NettyMessageFactory.PING_MSG) {
            heartbeatCount++;
            System.out.println("Client get pong msg from " + ctx.channel().remoteAddress());

            //回复一个Pong
            ctx.writeAndFlush(NettyMessageFactory.buildHeartBag(NettyMessageFactory.PONG_MSG, heartbeatCount));
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    /**
     * 读写超时时触发,将通道关闭
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // IdleStateHandler 所产生的 IdleStateEvent 的处理逻辑.
        if (evt instanceof IdleStateEvent) {
            System.err.println("---client " + ctx.channel().remoteAddress().toString() + " reader timeout, close it---");
            ctx.close();
        }
    }
}
